//
//  CenterListVC.m
//  WuyouTang
//
//  Created by YunBao on 2018/6/14.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "CenterListVC.h"

#import "NearbyVideoModel.h"
#import "CenterListCell.h"
#import "YBGetVideoObj.h"

@interface CenterListVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
{
    BOOL canBackTop;
    NSString *pullurl;
    int _lookSawIdx;
    BOOL _onNextPage;
    BOOL _needScroToIdx;
}

@property(nonatomic,assign)int paging;
@property(nonatomic,strong)UIImageView *backimage;
@property(nonatomic,strong)NSMutableArray *videoArray;
@property(nonatomic,strong)NSArray *models;

@property(nonatomic,strong)UIView *justSawView;//  刚刚看过
@property(nonatomic,strong)UIImageView *justSawIV;

@end

@implementation CenterListVC

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_listType == ListType_Normal) {
        [PublicView hideCenterGif:nil];
    }
    [self removeJustSawView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([[Config getOwnID] intValue] <= 0) {
        
    }else{
        [self pullData];

    }
}

-(NSArray *)models{
    NSMutableArray *m_array = [NSMutableArray array];
    for (NSDictionary *dic in self.videoArray) {
        NearbyVideoModel *model = [NearbyVideoModel modelWithDictionary:dic];
        [m_array addObject:model];
    }
    _models = m_array;
    return _models;
}

-(void)pullData {
    
    if (_listType == ListType_Normal) {
       pullurl = [NSString stringWithFormat:@"Video.getHomeVideo&touid=%@&p=%d",_otherUid,_paging];
    }else if(_listType == ListType_Likes){
       pullurl = [NSString stringWithFormat:@"User.getLikeVideos&touid=%@&p=%d",_otherUid,_paging];
    }else{
        pullurl = [NSString stringWithFormat:@"User.getCollectionVideos&touid=%@&p=%d",_otherUid,_paging];
    }
    [WYNetworking postWithUrl:pullurl Dic:nil Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_footer endRefreshing];
        [_collectionView.mj_header endRefreshing];
        if (code == 0) {
            NSArray *infoA = [NSArray arrayWithArray:info];
            if (_paging==1) {
                [_videoArray removeAllObjects];
            }
            if (infoA.count>0) {
                [_videoArray addObjectsFromArray:infoA];
                
            }else{
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            [self pubNoData];
            [_collectionView reloadData];
            
            // 显示刚刚看过
            if (_listType == ListType_Normal && ![PublicObj checkNull:_foryouVideoId]) {
                _justSawView.hidden = NO;
                [self forVideoIdx];
            }
            
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        [_collectionView.mj_footer endRefreshing];
        [_collectionView.mj_header endRefreshing];
        [self pubNoData];
    }];
}
-(void)pubNoData {
    if (_listType == ListType_Normal && [_otherUid isEqual:[Config getOwnID]]) {
        if (_videoArray.count > 0) {
            [PublicView hideCenterGif:nil];
        }else{
            [PublicView showCenterGif:nil];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviView.hidden = YES;
    self.view.backgroundColor = RGB(245, 245, 245);
    _paging = 1;
    self.videoArray = [NSMutableArray array];
    [self.view addSubview:self.collectionView];
    
    canBackTop = NO;
    _needScroToIdx = NO;
    
    // NSLog(@"foryouvideoid:%@",_foryouVideoId);
    _lookSawIdx = -1;
    _onNextPage = NO;
    UIView *keyWindow = [UIApplication sharedApplication].delegate.window;
    [keyWindow addSubview:self.justSawView];
    [_justSawView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(keyWindow.mas_right).offset(-20);
        make.bottom.equalTo(keyWindow.mas_bottom).offset(-20-ShowDiff/2);
        make.height.mas_equalTo(40);
    }];
}

/// 刚刚看过 start
- (UIView *)justSawView {
    if (!_justSawView) {
        _justSawView = [[UIView alloc]init];
        _justSawView.backgroundColor = RGB_COLOR(@"#555555", 1);
        _justSawView.layer.cornerRadius = 10;
        _justSawView.layer.masksToBounds = YES;
        _justSawView.hidden = YES;
        
        UILabel *titL = [[UILabel alloc]init];
        titL.font = SYS_Font(14);
        titL.textColor = UIColor.whiteColor;
        titL.text = @"刚刚看过";
        titL.textColor = UIColor.whiteColor;
        [_justSawView addSubview:titL];
        [titL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_justSawView.mas_left).offset(12);
            make.centerY.equalTo(_justSawView);
        }];
        
        UIImageView *arrowIV = [[UIImageView alloc]init];
        arrowIV.image = [UIImage imageNamed:@"wyt_arrow_down"];
        _justSawIV = arrowIV;
        [_justSawView addSubview:arrowIV];
        [arrowIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(12);
            make.left.equalTo(titL.mas_right).offset(4);
            make.right.equalTo(_justSawView.mas_right).offset(-12);
            make.centerY.equalTo(_justSawView);
        }];
        UIButton *shadowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [shadowBtn addTarget:self action:@selector(startScrollToView) forControlEvents:UIControlEventTouchUpInside];
        [_justSawView addSubview:shadowBtn];
        [shadowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.centerX.centerY.equalTo(_justSawView);
        }];
    }
    return _justSawView;
}
-(void)startScrollToView {
    if (_onNextPage) {
        // 请求接口：获取更多数据获取下标
        _needScroToIdx = YES;
        _paging += 1;
        [self pullData];
    }else {
        // 直接滚动到当前视频
        [self viewScrotoLookItem];
    }
}

-(void)viewScrotoLookItem {
    if (_lookSawIdx < 0 || (_lookSawIdx+1) > _videoArray.count) {
        return;
    }
    if (_lookSawIdx>2) {
        // 超过某个数值，主scrollView滚动到底部
        if (self.sawEvent) {
            self.sawEvent();
        }
    }
    // collectionView滚动
    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForItem:_lookSawIdx inSection:0];
    UICollectionViewScrollPosition scrPosition = UICollectionViewScrollPositionCenteredVertically;
    if ((_lookSawIdx+2)>=_videoArray.count) {
        scrPosition = UICollectionViewScrollPositionBottom;
    }
    [_collectionView scrollToItemAtIndexPath:scrollIndexPath atScrollPosition:scrPosition animated:YES];
    [self removeJustSawView];
}

-(void)removeJustSawView {
    if (_justSawView) {
        [_justSawView removeFromSuperview];
        _justSawView = nil;
    }
    _onNextPage = NO;
    _needScroToIdx = NO;
}
//
-(void)forVideoIdx {
    BOOL have = NO;
    for (int i=0; i<_videoArray.count; i++) {
        NSDictionary *subDic = _videoArray[i];
        if ([_foryouVideoId isEqual:strFormat([subDic valueForKey:@"id"])]) {
            have = YES;
            _onNextPage = NO;
            _lookSawIdx = i;
            break;
        }
    }

    if (have == NO) {
        // 说明不在当前_paging这一页：自己请求下一页数据
        _onNextPage = YES;
    }
   
    /// 点击了”刚刚看过,请求到数据直接滚动“
    if (_needScroToIdx) {
        if (have) {
            [self viewScrotoLookItem];
        }else {
            // 说明本页没有继续寻找下一页
            _paging += 1;
            [self pullData];
        }
    }
   
}
/// 刚刚看过 end

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark - UICollectionViewDataSource
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionFooter){
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"space_footer" forIndexPath:indexPath];
        view.backgroundColor = UIColor.whiteColor;
        return view;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;{
    return CGSizeMake(_window_width,ShowDiff);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.models.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CenterListCell *cell = (CenterListCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"CenterListCell" forIndexPath:indexPath];
    cell.model = _models[indexPath.row];
    if (_lookSawIdx == indexPath.row) {
        cell.lookSawV.hidden = NO;
    }else {
        cell.lookSawV.hidden = YES;
    }
    return cell;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *videoDic = _videoArray[indexPath.row];
    NSString *vidoeID = minstr([videoDic valueForKey:@"id"]);
    [YBGetVideoObj lookManeger].fromWhere = @"CenterVC";
    [YBGetVideoObj lookManeger].videoID = vidoeID;
    [YBGetVideoObj lookManeger].playIndex = (int)indexPath.row;
    [YBGetVideoObj lookManeger].videoList = [_videoArray mutableCopy];
    [YBGetVideoObj lookManeger].paging = _paging;
    [YBGetVideoObj lookManeger].baseUrl = pullurl;
    [[YBGetVideoObj lookManeger]goLookVC];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSLog(@"lsitvc=====%f===%d",scrollView.contentOffset.y,_collectionView.scrollEnabled);
    if (scrollView.contentOffset.y<=-50) {
        canBackTop = YES;
    }else{
       canBackTop = NO;
    }
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (canBackTop == YES) {
        [self.delegate listScrollToTop:velocity.y];
    }
}
#pragma mark - set/get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(_window_width/3-1, _window_width/3*4/3);
        flow.minimumLineSpacing = 1;
        flow.minimumInteritemSpacing = 0.5;
        CGFloat HH = _window_height-44-64-49-statusbarHeight;
        if (!_isTabbar) {
            HH = _window_height-44-64-statusbarHeight;
        }
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, _window_width, HH) collectionViewLayout:flow];
        [self.collectionView registerNib:[UINib nibWithNibName:@"CenterListCell" bundle:nil] forCellWithReuseIdentifier:@"CenterListCell"];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate =self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.scrollEnabled = NO;
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"space_footer"];
        _collectionView.emptyDataSetSource = self;
        _collectionView.emptyDataSetDelegate = self;
        _collectionView.mj_insetB = -ShowDiff;
        YBWeakSelf;
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.paging = 1;
            [self pullData];
        }];
        self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weakSelf.paging +=1;
            [self pullData];
        }];
    }
    return _collectionView;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *text = @"";
    if (_listType == ListType_Normal && ![_otherUid isEqual:[Config getOwnID]]) {
        text = YZMsg(@"TA还没有作品");
    }else if (_listType == ListType_Likes && ![_otherUid isEqual:[Config getOwnID]]){
        text = YZMsg(@"TA还没有喜欢的视频");
    }else if (_listType == ListType_Collection && ![_otherUid isEqual:[Config getOwnID]]){
        text = YZMsg(@"TA还没有收藏的视频");
    }else if (_listType == ListType_Likes && [_otherUid isEqual:[Config getOwnID]]){
        text = YZMsg(@"你赞过的作品都会放到这里");
    }else if (_listType == ListType_Collection){
        text = YZMsg(@"你收藏的作品都会放到这里");
    }
    NSDictionary *attributes = @{NSFontAttributeName: ybNodataFont,
                                 NSForegroundColorAttributeName: ybNodataCol};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
    CGFloat moveY = -(statusbarHeight+64+44);
    return moveY;
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return NO;
}



@end
